package EGS.impl;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import com.google.gson.Gson;

import LOGISTICS.c_material;
import LOGISTICS.m_material;
import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.URLapi;
import WORKPLACE.stationClient;

public class EGS_execute_service590Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 590 物料状态变更（卸载和耗尽）
	 */
	public EGS_execute_service590Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		String msgClass = "";
		try {
			if (MSG == null) {
				return null;
			}
			Element Mroot = MSG.getRootElement();
			msgClass = Mroot.element("header").attribute("messageClass").getValue();
			String iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();

			if (msgClass.equals("590")) {// 物料状态变更（卸载和耗尽）
				String str = Mroot.element("body").element("operation").attribute("type").getValue();
				if (str.length() < 1) {
					str = "1";
				}

				/**
				 * 2=卸载物料 3=物料数量清零
				 */
				String isUnmount = str;
				String op = Mroot.element("body").element("operation").attribute("operator").getValue();
				String time = Mroot.element("body").element("operation").attribute("timestamp").getValue();
				String iMaterialID = Mroot.element("body").element("operation").attribute("materialID").getValue();
				String tips = Mroot.element("body").element("operation").attribute("reason").getValue();
				String cartID = "";
				try {
					cartID = Mroot.element("body").element("operation").attribute("cartID").getValue();
				} catch (Exception e3) {
					;
				}
				if (cartID == null || cartID.length() < 1) {
					cartID = "NA";
				}
				String quantity = "-1";
				try {
					quantity = Mroot.element("body").element("material").attribute("qty").getValue();
				} catch (Exception e3) {
					;
				}

				Mroot.remove(Mroot.element("body"));
				Element eleB = Mroot.addElement("body");
				Element eleR = eleB.addElement("result");

				c_material cm = new c_material(sql);
				m_material iReel = cm.getMaterial(iMaterialID);
				try {
					if(iReel.location!=null && iReel.location.equals("WMS")) {// materialLOG 记录卸载
						cm.logMaterial(0, op, time, iMaterialID, Double.parseDouble(quantity), iStation,
								cartID + "@NA" , "NA", tips+"@该物料已退库未领料","NA");
						throw new Exception("-185");//该物料已退库未领料
					}
					JTable t = sql.select("select location,feeder from materialLog where " + "materialID='"
							+ iMaterialID + "' and state>0 " + "order by createTime desc");// 查找被扫描的那盘料
					if (t == null || t.getRowCount() < 1) {
						throw new Exception("-180");// 查不到报错
					}
					String location1 = (String) t.getValueAt(0, 0);
					String[] locator = location1.split("@");
					if (locator.length > 1) {
						location1 = locator[1];
					}
					String location = location1;
					String feeder = (String) t.getValueAt(0, 1);
					String iqty = quantity;
					String icartID = cartID;
					Thread iTH = new Thread(new Runnable() {// 查到了准备卸载
						int istate = Integer.parseInt(isUnmount);
						String iOP = op;
						String iTime = time;
						String oMaterial = iMaterialID;
						String iiStation = iStation;
						String iicartID = icartID;
						String iLocation = location;
						String iFeeder = feeder;
						String iTips = tips;
						String iiqty = iqty;
						m_material sReel = iReel;

						@Override
						public void run() {
							try {
								String mlocation = iiStation + "@" + iicartID + "@" + iLocation;
								double sqty = Double.parseDouble(iiqty);
								c_material cmt = new c_material(sql);
								try {
									String oOrder=getStationOrder(iiStation);
									cmt.logMaterial(0, iOP, iTime, oMaterial, sqty, iiStation,
											iicartID + "@" + iLocation, iFeeder, iTips,oOrder);
									if (istate == 2) {// 卸载
										String str = "update setupLocation set cartID='',feeder='',reel='',"
												+ "nextReel='',lastEdit=GETDATE() where reel='" + oMaterial + "'";
										sql.Command(str);
										str = "update materialID set location='lineBIN',quantity=" + iiqty
												+ " where materialID='" + oMaterial + "'";
										sql.Command(str);
										updateLocation(oMaterial,"lineBIN");
										m_material nReel = null;
										if (sReel.nextReel != null && sReel.nextReel.length() > 0) {// 末端所有接料都要改成LineBIN
											str = "update materialID set location='lineBIN' where materialID='"
													+ sReel.nextReel + "'";
											sql.Command(str);
											updateLocation(sReel.nextReel,"lineBIN");
											nReel = cm.getMaterial(sReel.nextReel);
											cmt.logMaterial(0, iOP, iTime, nReel.materialID, nReel.quantity, iiStation,
													iicartID + "@" + iLocation, iFeeder, iTips+"["+nReel.preReel+"的接料]",oOrder);
											boolean b = (nReel.nextReel != null && nReel.nextReel.length() > 0);
											int flag=0;
											while (b && flag <5) {
												str = "update materialID set location='lineBIN' where materialID='"
														+ nReel.nextReel + "'";
												sql.Command(str);
												updateLocation(nReel.nextReel,"lineBIN");
												nReel = cm.getMaterial(nReel.nextReel);
												cmt.logMaterial(0, iOP, iTime, nReel.materialID, nReel.quantity, iiStation,
														iicartID + "@" + iLocation, iFeeder, iTips+"["+nReel.preReel+"的接料]",oOrder);
												b = (nReel.nextReel != null && nReel.nextReel.length() > 0);
												flag+=1;
											}
										}
									} else if (istate == 3) {// 物料用光
										m_material nReel = null;
										if (sReel.nextReel != null && sReel.nextReel.length() > 0) {
											nReel = cm.getMaterial(sReel.nextReel);
										}
										String str = "update materialID set quantity=0,location='lineBIN' where materialID='"
												+ sReel.materialID + "'";
										sql.Command(str);
										updateLocation(sReel.materialID,"lineBIN");
										if (nReel != null) {
											str = "update setupLocation set reel='" + nReel.materialID + "',nextReel='"
													+ nReel.nextReel + "',quantity=" + nReel.quantity
													+ ",lastEdit=GETDATE() where reel='" + sReel.materialID + "'";
											sql.Command(str);
											str = "update materialID set location='" + mlocation
													+ "',preReel='' where materialID='" + nReel.materialID + "'";
											sql.Command(str);
											updateLocation(nReel.materialID,mlocation);
											cmt.logMaterial(1, iOP, iTime, nReel.materialID, nReel.quantity, iiStation,
													iicartID + "@" + iLocation, iFeeder, "接料启用",oOrder);
										} else {
											str = "update setupLocation set cartID='',reel='',nextReel='',quantity=0,lastEdit=GETDATE() where reel='"
													+ sReel.materialID + "'";
											sql.Command(str);
										}
									}
								} catch (Exception e3) {
//									String str=errCodeManagement.getErrText(e3.getMessage());
									;
								}
							} catch (Exception e2) {
//								String str=errCodeManagement.getErrText(e2.getMessage());
								;
							}
//							try {
//								iisql.close();
//							}catch(Exception e1) {
//								;
//							}
						}
					});
					iTH.start();

					eleR.addAttribute("errorCode", "0");
					eleR.addAttribute("errorText", "Valid");
					eleR.addAttribute("actionCode", "0");
					AKSLogs(5901, cartID + "_" + iStation + "_" + iMaterialID);
//					return null;
				} catch (Exception e) {
					str = errCodeManagement.getErrText(e.getMessage());
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", "0");
					AKSLogs(5900, cartID + "_" + iStation + "_" + iMaterialID + "_" + str);
				}
			} else {
				isUnknowCase = true;
				return null;
			}
			return MSG;
		} catch (Exception e) {
			if(iClient==null) {
				Element Mroot = MSG.getRootElement();
				Element eleR = Mroot.element("body").addElement("result");
				eleR.addAttribute("errorCode", "1");
				eleR.addAttribute("errorText", "工位信息获取失败");
				eleR.addAttribute("actionCode", "0");
				return MSG;
			}
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			return null;
		}

	}
	
	public void updateLocation(String materialID,String location) {
		URLapi aa=new URLapi();//
		aa.RESTInvoker("http://192.168.0.220:8081", "","");
		Location4material poster=new Location4material();
		poster.setRid(materialID);
		poster.setLocation(location);
		String ijson=new Gson().toJson(poster);
		aa.putDataToServer("/api/materialLogistics/material/location", ijson);
	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}
	
	private String getStationOrder(String iStation) throws Exception {
		if(iStation.endsWith("NPM-M2")) {// 应对M2不激活工单的特殊设定
			iStation=iStation.replaceAll("-M2", "-M1");
		}
		String str="select orderNumber from assetStation where ID='"+iStation+"'";
		JTable t=sql.select(str);
		String oOrder="";
		if(t!=null && t.getRowCount()>0) {
			oOrder=""+t.getValueAt(0, 0);
		}else {
			if(iStation.endsWith("M2")) {// 应对M2不激活工单的特殊设定
				iStation=iStation.replaceAll("-M2", "-M1");
			}
			str="select orderNumber from assetStation where ID='"+iStation+"'";
			t=sql.select(str);
			if(t!=null && t.getRowCount()>0) {
				oOrder=""+t.getValueAt(0, 0);
			}
		}
		return oOrder;
	}

}
